using LitJson;
namespace CGF
{
    public partial class PanelEditUserInfo : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        private string columnName, columnKey, defaultValue;

        public static void Open(string columnName, string columnKey, string defaultValue)
        {
            UIManagerComponent.instance.OpenUI<PanelEditUserInfo>(UILayer.Normal, RootComponent.instance, true).SetInfo(columnName, columnKey, defaultValue);
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<PanelEditUserInfo>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelEditUserInfo", layer, isFloat);
            BindProperties(transform);

            BtnClose.SetClick(Close);

            if (columnName != null)
            {
                SetInfo(columnName, columnKey, defaultValue);
            }

            BtnConfirm.SetClick(async () =>
            {
                JsonData data = new JsonData();
                data[columnKey] = InputField.text;
                var res = await Network.Post("/v1/reward/oauth/change", data);
                if (res.success)
                {
                    JsonData info = UserInfo.Info;
                    info[columnKey == "user_name" ? "name" : columnKey] = InputField.text;
                    UserInfo.Info = info;
                    EventManager.Emit(new Event_UserInfoUpdate());
                    CGF.Dialog.Alert(I18N_edit_success, Close);
                }
            });
            
            ScaleIn(Dialog.transform);
        }

        private void SetInfo(string columnName, string columnKey, string defaultValue)
        {
            this.columnName = columnName;
            this.columnKey = columnKey;
            this.defaultValue = defaultValue;
            if (!BtnConfirm) return;

            Title.text = $"{I18N_modify}{this.columnName}";
            InputField.text = defaultValue;
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

    }
}
